"use client"

import type React from "react"
import {useState} from "react"
import {Button} from "@/components/ui/button"
import {Input} from "@/components/ui/input"
import {Label} from "@/components/ui/label"
import {Checkbox} from "@/components/ui/checkbox"
import {EyeIcon, EyeOffIcon, Loader2} from "lucide-react"

interface LoginResponse {
    code: number
    data?: string
    message?: string
}

export function PasswordLoginForm() {
    const [loading, setLoading] = useState(false)
    const [showPassword, setShowPassword] = useState(false)
    const [formData, setFormData] = useState({
        username: "",
        password: "",
        remember: false,
    })

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const {name, value} = e.target
        setFormData((prev) => ({...prev, [name]: value}))
    }

    const handleCheckboxChange = (checked: boolean) => {
        setFormData((prev) => ({...prev, remember: checked}))
    }

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        setLoading(true)

        try {
            const response = await fetch('http://127.0.0.1:9080/basin-auth/sign-in', { // 替换为你的实际接口地址
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: formData.username,
                    password: formData.password,
                    remember: formData.remember
                })
            })

            const data: LoginResponse = await response.json()

            if (data.code === 200) {
                // 登录成功处理
                console.log('Login successful', data.data)
                // 示例：存储 token 到 localStorage
                if (data.data) localStorage.setItem('basintoken', data.data)
                // 跳转到受保护页面
                window.location.href = '/dashboard'
            } else {
                // 登录失败处理
                console.error('Login failed:', data.message)
                // 示例：显示错误提示
                alert(data.message || '登录失败，请检查凭证')
            }

        } catch (error) {
            console.error('Network error:', error)
            alert('网络连接失败，请稍后再试')
        } finally {
            setLoading(false)
        }
    }

    return (
        <form onSubmit={handleSubmit} className="space-y-4 py-4">
            <div className="space-y-2">
                <Label htmlFor="username">账号</Label>
                <Input
                    id="username"
                    name="username"
                    placeholder="请输入账号"
                    required
                    value={formData.username}
                    onChange={handleChange}
                />
            </div>

            <div className="space-y-2">
                <Label htmlFor="password">密码</Label>
                <div className="relative">
                    <Input
                        id="password"
                        name="password"
                        type={showPassword ? "text" : "password"}
                        placeholder="请输入密码"
                        required
                        value={formData.password}
                        onChange={handleChange}
                    />
                    <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="absolute right-0 top-0 h-full px-3 py-2 text-gray-400 hover:text-gray-600"
                        onClick={() => setShowPassword(!showPassword)}
                    >
                        {showPassword ? <EyeOffIcon className="h-4 w-4"/> : <EyeIcon className="h-4 w-4"/>}
                    </Button>
                </div>
            </div>

            <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                    <Checkbox id="remember" checked={formData.remember} onCheckedChange={handleCheckboxChange}/>
                    <Label htmlFor="remember" className="text-sm font-normal">
                        记住我
                    </Label>
                </div>
                <a href="#" className="text-sm font-medium text-blue-600 hover:text-blue-500">
                    忘记密码?
                </a>
            </div>

            <Button type="submit" className="w-full" disabled={loading}>
                {loading ? (
                    <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin"/>
                        登录中...
                    </>
                ) : (
                    "登录"
                )}
            </Button>
        </form>
    )
}
